/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package project.jpdftools.ui.actionlisteners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.logging.Level;
import project.jpdftools.ui.logic.JPDF;
import project.jpdftools.managers.LoggerManager;
import project.jpdftools.ui.MainMenu;

/**
 *
 * @author Mido
 */
public class RemoveComponentAction implements ActionListener {

    private JPDF component;

    public RemoveComponentAction(JPDF component) {
        super();
        this.component = component;
    }

    public void actionPerformed(ActionEvent evt) {
        // remove the component with the specified id from the arraylist
        JPDF jpdf = (JPDF) component;
        if (MainMenu.getInstance().getJpdf_data().size() != 1) {
            MainMenu.getInstance().getJpdf_data().remove(jpdf.getId());
        } else {
            MainMenu.getInstance().getJpdf_data().remove(0);
        }
        // remove the component with the specified id from the UI
        MainMenu.getInstance().getP_right().remove(jpdf.getId());

        // update the remaining components IDs
        decrementComponentIDs();

        // update GUI
        MainMenu.getInstance().repaint();
        MainMenu.getInstance().validate();
        LoggerManager.getLogger().log(Level.INFO, "Component removed. Component ID = {0}", jpdf.getId());
    }

    /**
     * Decrement the JPDF components that has an ID greater than this component
     * ID
     */
    private void decrementComponentIDs() {
        ArrayList<JPDF> jpdf_list = MainMenu.getInstance().getJpdf_data();
        int component_id = component.getId();
        for (int i = component_id; i < jpdf_list.size(); i++) {
            jpdf_list.get(i).setId(jpdf_list.get(i).getId() - 1);
        }
    }
}
